<?php

namespace common\models;

use backend\models\AdminUser;
use common\traits\Model;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "{{%user}}".
 *
 * @property integer       $id
 * @property integer       $vip_type
 * @property integer       $vip_end
 * @property integer       $effect_time
 * @property string        $money
 * @property string        $username
 * @property string        $realname
 * @property integer       $sex
 * @property integer       $group_id
 * @property integer       $age
 * @property string        $birthday
 * @property string        $mobile
 * @property string        $birthday_month
 * @property string        $idcard
 * @property string        $wechat_id
 * @property string        $address
 * @property integer       $status
 * @property integer       $created_at
 * @property integer       $updated_at
 *
 * @property WechatUser    $wechatUser
 * @property UserCase      $userCase
 * @property Package       $package
 * @property UserGroup     $group
 * @property UserConsignee $consignee
 * @property AdminUser     $adminUser
 */
class User extends \yii\db\ActiveRecord implements IdentityInterface{
    use Model;
    
    const SCENARIO_COMPLETE = 'complete';
    
    /**
     * @inheritdoc
     */
    public static function tableName(){
        return '{{%user}}';
    }
    
    public function behaviors(){
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ]
            ]
        ];
    }
    
    public function scenarios(){
        $scenarios = parent::scenarios();
        $scenarios[self::SCENARIO_COMPLETE] = ['realname', 'birthday', 'idcard', 'age', 'sex', 'address'];
        return $scenarios;
    }
    
    /**
     * @inheritdoc
     */
    public function rules(){
        return [
            [['username', 'group_id', 'mobile'], 'required', 'on' => self::SCENARIO_DEFAULT],
            [['sex', 'group_id', 'age', 'status', 'created_at', 'updated_at', 'vip_type', 'vip_end', 'effect_time'], 'integer'],
            [['money'], 'number'],
            [['username', 'wechat_id', 'address'], 'string', 'max' => 255],
            [['realname', 'birthday', 'mobile', 'birthday_month', 'idcard'], 'string', 'max' => 32],
            [['realname', 'idcard', 'age', 'sex'], 'required', 'on' => self::SCENARIO_COMPLETE],
            ['mobile', 'match', 'pattern' => Yii::$app->params['match']['mobile']],
            ['mobile', 'unique', 'targetAttribute' => 'mobile', 'message' => '手机号已经注册'],
        
        ];
    }
    
    /**
     * @inheritdoc
     */
    public function attributeLabels(){
        return [
            'id' => 'ID',
            'username' => '用户名',
            'realname' => '真实姓名',
            'sex' => '性别',
            'group_id' => '人群',
            'effect_time' => '生效时间',
            'money' => '余额',
            'age' => '年龄',
            'birthday' => '生日',
            'mobile' => '电话',
            'birthday_month' => '出生年月',
            'idcard' => '身份证',
            'wechat_id' => '微信昵称',
            'address' => '家庭住址',
            'status' => 'Status',
            'created_at' => '注册时间',
            'updated_at' => 'Updated At',
        ];
    }
    
    public function getWechatUser(){
        return $this->hasOne(WechatUser::className(), ['openid' => 'wechat_id']);
    }
    
    
    /**
     * @inheritdoc
     */
    public static function findIdentity($id){
        return static::findOne(['id' => $id,]);
    }
    
    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null){
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }
    
    /**
     * @inheritdoc
     */
    public function getId(){
        return $this->getPrimaryKey();
    }
    
    /**
     * @inheritdoc
     */
    public function getAuthKey(){
    }
    
    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password){
    }
    
    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password){
    }
    
    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey(){
    }
    
    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey){
        return $this->getAuthKey() === $authKey;
    }
    
    
    /**
     * 判断是不是会员
     * @return bool
     */
    public function isVip(){
        return Yii::$app->user->identity->vip_type > 0 && Yii::$app->user->identity->vip_end > time();
    }
    
    /**
     * 判断是否需要完善信息
     * @return bool
     */
    public function isUserInfo(){
        return empty($this->idcard) ? true : false;
    }
    
    /**
     * 处理用户会员信息
     * @param VipOrder $order
     * @return bool
     */
    public function prepareVip(VipOrder $order){
        // 续费或首次购买
        if( $this->vip_type == $order->package_id || $this->vip_type <= 0 ){
            $time = $this->vip_end ?: time();
            $this->vip_end = $time + 3600 * 24 * 365;
            $this->vip_type = $order->package_id;
            return $this->save();
        }else{
            $old_order = VipOrder::find()->where(['user_id' => $order->user_id, 'package_id' => $this->vip_type])->one();
            //计算时间
            $day = ($order->created_at - $old_order->log->created_at) / (3600 * 24);
            $sy_money = $old_order->money - (365 / $old_order->money) * $day;
            // 重新计算生成时间
            $this->vip_type = $order->package_id;
            $this->vip_end = time() + 3600 * 24 * 365;
            $this->money += $sy_money;
            // 重新计算会员补贴有效期
            $this->effect_time = time() + $this->package->wait_time * 3600 * 24;
            return $this->save();
        }
        
    }
    
    public function getUsername()
    {
        return $this->realname ?: $this->username;
    }
    
    
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUserCase(){
        return $this->hasOne(UserCase::className(), ['user_id' => 'id']);
    }
    
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getConsignee(){
        return $this->hasOne(UserConsignee::className(), ['user_id' => 'id']);
    }
    
    public function getPackage(){
        return $this->hasOne(Package::className(), ['package_id' => 'vip_type']);
    }
    
    public function getGroup(){
        return $this->hasOne(UserGroup::className(), ['group_id' => 'group_id']);
    }
    
    public function getAdminUser()
    {
        return $this->hasOne(AdminUser::className(), ['mobile' => 'mobile']);
    }
    
    public function getPackageGroup(){
        $date = strtotime(substr($this->idcard, 6, 8));
//获得出生年月日的时间戳
        $today = strtotime('today');
//获得今日的时间戳 111cn.net
        $diff = floor(($today - $date) / 86400 / 365);
//得到两个日期相差的大体年数

//strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
        $age = strtotime(substr($this->idcard, 6, 8) . ' +' . $diff . 'years') > $today ? ($diff + 1) : $diff;
        
        if( $age >= 20 && $age < 30 ){
            $key = 1;
        }elseif( $age >= 30 && $age < 40 ){
            $key = 2;
        }elseif( $age >= 40 && $age < 50 ){
            $key = 3;
        }elseif( $age >= 50 && $age < 60 ){
            $key = 4;
        }elseif( $age > 60 ){
            $key = 5;
        }
        
        return 'package_price' . $key;
        
    }
    
}
